#include "register.h"
#include "ui_register.h"

Register::Register(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);

    Init();
}

Register::~Register()
{
    delete ui;
}

void Register::Init()
{
    ui->pBtn_Reg_Register->setFocus();
    ui->pBtn_Reg_Register->setDefault(true);
    ui->pBtn_Reg_Register->setShortcut(QKeySequence::InsertParagraphSeparator);
    ui->pBtn_Reg_Register->setShortcut(Qt::Key_Enter);
    ui->pBtn_Reg_Register->setShortcut(Qt::Key_Return); // 暂时没有反应

    UserId = -1;
}

bool Register::CheckInfoEmpty()
{
    if(ui->lineEdit_Reg_Mail->text().isEmpty()) {
        ui->label_Reg_TipInfo->setText("邮箱地址不能为空！");
        return false;
    }
    if(ui->lineEdit_Reg_User->text().isEmpty()) {
        ui->label_Reg_TipInfo->setText("昵称不能为空！");
        return false;
    }
    if(ui->lineEdit_Reg_Passwd->text().isEmpty()) {
        ui->label_Reg_TipInfo->setText("密码不能为空！");
        return false;
    }
    if(ui->lineEdit_Reg_sPasswd->text().isEmpty()) {
        ui->label_Reg_TipInfo->setText("确认密码不能为空！");
        return false;
    }

    return true;
}

/*
 * 返回值：true:表示用户已存在，false：表示用户不存在
 */
bool Register::IsUserExist()
{
    JMySql Jsql;
    QString SQL;
    SQL = QString("select * from LJJ_Users where Mail = '%1' or NickName = '%2'").
            arg(ui->lineEdit_Reg_Mail->text()).arg(ui->lineEdit_Reg_User->text());
    bool Flag = Jsql.IsUserExist(SQL);
    if(!Flag) {
        return false;
    }
    else {
        ui->label_Reg_TipInfo->setText("用户已存在，请重新输入...");
        return true;
    }
}

int Register::GetUserId()
{
    JMySql Jsql;

    return Jsql.GetMaxUserId();
}

bool Register::InsertUser()
{
    JMySql Jsql;
    QString SQL;
    SQL = QString("insert into LJJ_Users(ID, NickName, Passwd, Mail) "
                  "values('%1', '%2', '%3', '%4')").
            arg(UserId).
            arg(ui->lineEdit_Reg_User->text()).
            arg(ui->lineEdit_Reg_Passwd->text()).
            arg(ui->lineEdit_Reg_Mail->text());
    if(!Jsql.InsertUser(SQL)) {
        ui->label_Reg_TipInfo->setText("用户注册失败！");
        return false;
    }
    return true;
}

//*****************事件**********************
void Register::on_pBtn_Reg_Register_clicked()
{
    if(!CheckInfoEmpty())
        return;
    if(IsUserExist()) {
        return;
    }
    UserId = GetUserId() + 1;
    if(InsertUser())
        ui->label_Reg_TipInfo->setText("用户注册成功");
}
